<template>
  <div class="price-config">
    <div class="section-title">电价配置</div>

    <div class="price-content">
      <!-- 尖峰电价 -->
      <div class="price-item">
        <div class="price-left">
          <span class="price-label">尖峰电价:</span>
          <el-input
            v-model="localPriceConfig.peak.price"
            type="text"
            size="small"
            style="width: 150px; margin: 0 10px"
            readonly
          ></el-input>
          <span class="price-unit">元/kWh</span>
        </div>
        <div class="price-right">
          <div class="time-period-container">
            <div class="time-period-label">尖峰时段:</div>
            <div class="time-periods-wrapper">
              <div
                v-for="(period, index) in localPriceConfig.peak.timePeriods"
                :key="index"
                class="time-period-item"
              >
                <el-time-picker
                  v-model="localPriceConfig.peak.timePeriods[index]"
                  is-range
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时段"
                  end-placeholder="结束时段"
                  placeholder="选择时间范围"
                  size="small"
                  style="width: 280px"
                  readonly
                ></el-time-picker>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 高峰电价 -->
      <div class="price-item">
        <div class="price-left">
          <span class="price-label">高峰电价:</span>
          <el-input
            v-model="localPriceConfig.high.price"
            type="text"
            size="small"
            style="width: 150px; margin: 0 10px"
            readonly
          ></el-input>
          <span class="price-unit">元/kWh</span>
        </div>
        <div class="price-right">
          <div class="time-period-container">
            <div class="time-period-label">高峰时段:</div>
            <div class="time-periods-wrapper">
              <div
                v-for="(period, index) in localPriceConfig.high.timePeriods"
                :key="index"
                class="time-period-item"
              >
                <el-time-picker
                  v-model="localPriceConfig.high.timePeriods[index]"
                  is-range
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时段"
                  end-placeholder="结束时段"
                  placeholder="选择时间范围"
                  size="small"
                  style="width: 280px"
                  readonly
                ></el-time-picker>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 平段电价 -->
      <div class="price-item">
        <div class="price-left">
          <span class="price-label">平段电价:</span>
          <el-input
            v-model="localPriceConfig.flat.price"
            type="text"
            size="small"
            style="width: 150px; margin: 0 10px"
            readonly
          ></el-input>
          <span class="price-unit">元/kWh</span>
        </div>
        <div class="price-right">
          <div class="time-period-container">
            <div class="time-period-label">平段时段:</div>
            <div class="time-periods-wrapper">
              <div
                v-for="(period, index) in localPriceConfig.flat.timePeriods"
                :key="index"
                class="time-period-item"
              >
                <el-time-picker
                  v-model="localPriceConfig.flat.timePeriods[index]"
                  is-range
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时段"
                  end-placeholder="结束时段"
                  placeholder="选择时间范围"
                  size="small"
                  style="width: 280px"
                  readonly
                ></el-time-picker>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 低谷电价 -->
      <div class="price-item">
        <div class="price-left">
          <span class="price-label">低谷电价:</span>
          <el-input
            v-model="localPriceConfig.offPeak.price"
            type="text"
            size="small"
            style="width: 150px; margin: 0 10px"
            readonly
          ></el-input>
          <span class="price-unit">元/kWh</span>
        </div>
        <div class="price-right">
          <div class="time-period-container">
            <div class="time-period-label">低谷时段:</div>
            <div class="time-periods-wrapper">
              <div
                v-for="(period, index) in localPriceConfig.offPeak.timePeriods"
                :key="index"
                class="time-period-item"
              >
                <el-time-picker
                  v-model="localPriceConfig.offPeak.timePeriods[index]"
                  is-range
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时段"
                  end-placeholder="结束时段"
                  placeholder="选择时间范围"
                  size="small"
                  style="width: 280px"
                  readonly
                ></el-time-picker>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 深谷电价 -->
      <div class="price-item">
        <div class="price-left">
          <span class="price-label">深谷电价:</span>
          <el-input
            v-model="localPriceConfig.superOffPeak.price"
            type="text"
            size="small"
            style="width: 150px; margin: 0 10px"
            readonly
          ></el-input>
          <span class="price-unit">元/kWh</span>
        </div>
        <div class="price-right">
          <div class="time-period-container">
            <div class="time-period-label">深谷时段:</div>
            <div class="time-periods-wrapper">
              <div
                v-for="(period, index) in localPriceConfig.superOffPeak
                  .timePeriods"
                :key="index"
                class="time-period-item"
              >
                <el-time-picker
                  v-model="localPriceConfig.superOffPeak.timePeriods[index]"
                  is-range
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时段"
                  end-placeholder="结束时段"
                  placeholder="选择时间范围"
                  size="small"
                  style="width: 280px"
                  readonly
                ></el-time-picker>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 电价曲线 -->
    <div class="price-curve">
      <div class="section-title">电价曲线</div>
      <div class="curve-chart">
        <nt-echart :options="priceCurveOptions" />
      </div>
    </div>
  </div>
</template>

<script>
import ntEchart from '@/components/nt-echart.vue'

export default {
  name: 'PriceConfig',
  components: {
    ntEchart
  },
  props: {
    priceConfig: {
      type: Object,
      default: () => ({
        peak: { price: '0.00', timePeriods: [] },
        high: { price: '0.00', timePeriods: [] },
        flat: { price: '0.00', timePeriods: [] },
        offPeak: { price: '0.00', timePeriods: [] },
        superOffPeak: { price: '0.00', timePeriods: [] }
      })
    },
    priceSchemeData: {
      type: Object,
      default: null
    },
    selectedMonth: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      localPriceConfig: {
        peak: {
          price: this.priceConfig?.peak?.price ?? '0.00',
          timePeriods: this.normalizeTimePeriods(
            this.priceConfig?.peak?.timePeriods || []
          )
        },
        high: {
          price: this.priceConfig?.high?.price ?? '0.00',
          timePeriods: this.normalizeTimePeriods(
            this.priceConfig?.high?.timePeriods || []
          )
        },
        flat: {
          price: this.priceConfig?.flat?.price ?? '0.00',
          timePeriods: this.normalizeTimePeriods(
            this.priceConfig?.flat?.timePeriods || []
          )
        },
        offPeak: {
          price: this.priceConfig?.offPeak?.price ?? '0.00',
          timePeriods: this.normalizeTimePeriods(
            this.priceConfig?.offPeak?.timePeriods || []
          )
        },
        superOffPeak: {
          price: this.priceConfig?.superOffPeak?.price ?? '0.00',
          timePeriods: this.normalizeTimePeriods(
            this.priceConfig?.superOffPeak?.timePeriods || []
          )
        }
      },
      priceCurveOptions: {}
    }
  },
  watch: {
    priceConfig: {
      handler(newVal) {
        if (newVal) {
          this.localPriceConfig = {
            peak: {
              price: newVal.peak?.price ?? '0.00',
              timePeriods: this.normalizeTimePeriods(
                newVal.peak?.timePeriods || []
              )
            },
            high: {
              price: newVal.high?.price ?? '0.00',
              timePeriods: this.normalizeTimePeriods(
                newVal.high?.timePeriods || []
              )
            },
            flat: {
              price: newVal.flat?.price ?? '0.00',
              timePeriods: this.normalizeTimePeriods(
                newVal.flat?.timePeriods || []
              )
            },
            offPeak: {
              price: newVal.offPeak?.price ?? '0.00',
              timePeriods: this.normalizeTimePeriods(
                newVal.offPeak?.timePeriods || []
              )
            },
            superOffPeak: {
              price: newVal.superOffPeak?.price ?? '0.00',
              timePeriods: this.normalizeTimePeriods(
                newVal.superOffPeak?.timePeriods || []
              )
            }
          }
        }
      },
      deep: true,
      immediate: true
    },
    priceSchemeData: {
      handler() {
        this.loadPriceConfigFromScheme()
      },
      deep: true
    },
    selectedMonth: {
      handler() {
        this.loadPriceConfigFromScheme()
      }
    },
    localPriceConfig: {
      handler() {
        this.updatePriceCurve()
      },
      deep: true
    }
  },
  mounted() {
    // 组件挂载时，如果已有电价方案数据和月份，则加载数据
    if (this.priceSchemeData && this.selectedMonth) {
      this.loadPriceConfigFromScheme()
    }
    // 初始化电价曲线
    this.updatePriceCurve()
  },
  methods: {
    // 将时间字符串转换为分钟数
    timeToMinutes(time) {
      const [hours, minutes] = time.split(':').map(Number)
      return hours * 60 + minutes
    },
    // 根据电价配置生成24小时的电价曲线数据
    generatePriceCurveData() {
      // 初始化24小时数据，每个小时有60个数据点（每分钟一个点）
      const minutesPerDay = 24 * 60
      const priceData = new Array(minutesPerDay).fill(0)

      // 费率类型映射
      const rateTypes = [
        {
          key: 'peak',
          price: parseFloat(this.localPriceConfig.peak.price) || 0
        },
        {
          key: 'high',
          price: parseFloat(this.localPriceConfig.high.price) || 0
        },
        {
          key: 'flat',
          price: parseFloat(this.localPriceConfig.flat.price) || 0
        },
        {
          key: 'offPeak',
          price: parseFloat(this.localPriceConfig.offPeak.price) || 0
        },
        {
          key: 'superOffPeak',
          price: parseFloat(this.localPriceConfig.superOffPeak.price) || 0
        }
      ]

      // 遍历每个费率类型，填充对应时段的价格
      rateTypes.forEach((rateType) => {
        const timePeriods =
          this.localPriceConfig[rateType.key].timePeriods || []
        timePeriods.forEach((period) => {
          if (period && Array.isArray(period) && period.length === 2) {
            const [startTime, endTime] = period
            if (startTime && endTime) {
              const startMinutes = this.timeToMinutes(startTime)
              const endMinutes = this.timeToMinutes(endTime)

              // 填充该时间段内的所有分钟
              for (
                let minutes = startMinutes;
                minutes < endMinutes;
                minutes++
              ) {
                if (minutes >= 0 && minutes < minutesPerDay) {
                  priceData[minutes] = rateType.price
                }
              }
            }
          }
        })
      })

      // 将每分钟的数据聚合为每小时的数据（取每小时的平均值或第一个值）
      // 这里我们取每小时第一个数据点的值，因为时段是连续的
      const hourlyData = []
      for (let hour = 0; hour < 24; hour++) {
        const hourStartMinutes = hour * 60
        hourlyData.push(priceData[hourStartMinutes] || 0)
      }

      return hourlyData
    },
    // 更新电价曲线
    updatePriceCurve() {
      const hours = Array.from({ length: 24 }, (_, idx) =>
        idx.toString().padStart(2, '0')
      )
      const priceData = this.generatePriceCurveData()

      // 计算Y轴的最大值（价格的最大值，向上取整到合适的值）
      const maxPrice = Math.max(...priceData, 0)
      const yAxisMax = maxPrice > 0 ? Math.ceil(maxPrice * 1.2) : 1

      this.priceCurveOptions = {
        color: ['#409EFF'],
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const item = params[0]
            return `${item.axisValue}时：${item.data} 元/kWh`
          }
        },
        grid: {
          left: 40,
          right: 20,
          top: 40,
          bottom: 30,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hours,
          boundaryGap: false,
          axisLabel: {
            formatter: (val) => `${val}时`
          }
        },
        yAxis: {
          type: 'value',
          name: '元/kWh',
          min: 0,
          max: yAxisMax,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#dcdfe6'
            }
          }
        },
        series: [
          {
            name: '电价',
            type: 'line',
            step: 'end',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            itemStyle: {
              color: '#409EFF',
              borderColor: '#fff',
              borderWidth: 1.5
            },
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.2)'
            },
            data: priceData
          }
        ]
      }
    },
    // 标准化时间段格式，兼容旧格式和新格式
    normalizeTimePeriods(periods) {
      if (!periods || periods.length === 0) {
        return [null]
      }
      return periods.map((period) => {
        if (Array.isArray(period)) {
          return period
        } else if (period && period.startTime && period.endTime) {
          return [period.startTime, period.endTime]
        } else {
          return null
        }
      })
    },
    // 格式化价格输入：只允许数字和小数点，最多6位小数
    formatPriceInput(type) {
      let value = this.localPriceConfig[type].price

      // 只允许输入数字和小数点
      value = value.replace(/[^\d.]/g, '')

      // 只允许一个小数点：如果有多个小数点，只保留第一个
      const parts = value.split('.')
      if (parts.length > 2) {
        // 如果有多个小数点，只保留第一个和第二个部分，去掉后面的所有部分
        value = parts[0] + '.' + parts.slice(1).join('')
      }

      // 处理连续的小数点
      value = value.replace(/\.{2,}/g, '.')

      // 处理前导0：不能以0开头，除非后面是小数点或本身就是单独的0
      if (value.length > 1 && value.startsWith('0')) {
        // 如果第二个字符不是小数点，则去掉前导0
        if (value[1] !== '.') {
          value = value.replace(/^0+/, '')
        }
      }

      // 保证小数点后最多6位
      const finalParts = value.split('.')
      if (finalParts.length === 2) {
        // 如果有小数点，限制小数部分最多6位
        if (finalParts[1].length > 6) {
          value = finalParts[0] + '.' + finalParts[1].substring(0, 6)
        }
      }

      // 直接更新绑定的值
      this.$set(this.localPriceConfig[type], 'price', value)

      this.emitUpdate()
    },
    // 处理价格输入框失焦：如果为空则设置为0.00
    handlePriceBlur(type) {
      const value = this.localPriceConfig[type].price
      // 如果为空或仅包含空格，则设置为0.00
      if (!value || value.trim() === '') {
        this.$set(this.localPriceConfig[type], 'price', '0.00')
        this.emitUpdate()
      }
    },
    // 将时间段字符串转换为时间段范围数组
    // 例如："0900,0915,0930,0945,1000,1015,1030,1045,1500,1515,1530,1545,1600,1615,1630,1645"
    // 时间间隔为15分钟，转换为：[["09:00", "11:00"], ["15:00", "17:00"]]
    parseTimePeriods(timeStr, interval) {
      if (!timeStr || timeStr.trim() === '') {
        return []
      }

      // 将时间段字符串转换为时间数组（格式：HHmm -> HH:mm）
      const timeArray = timeStr
        .split(',')
        .map((t) => {
          const trimmed = t.trim()
          if (trimmed.length === 4) {
            return `${trimmed.substring(0, 2)}:${trimmed.substring(2, 4)}`
          }
          return null
        })
        .filter((t) => t !== null)
        .sort()

      if (timeArray.length === 0) {
        return []
      }

      // 将时间转换为分钟数，方便计算
      const timeToMinutes = (time) => {
        const [hours, minutes] = time.split(':').map(Number)
        return hours * 60 + minutes
      }

      const minutesToTime = (minutes) => {
        const hours = Math.floor(minutes / 60)
          .toString()
          .padStart(2, '0')
        const mins = (minutes % 60).toString().padStart(2, '0')
        return `${hours}:${mins}`
      }

      // 将时间数组转换为分钟数数组
      const minutesArray = timeArray.map(timeToMinutes)

      // 找出连续的时间段
      const ranges = []
      let rangeStart = minutesArray[0]
      let rangeEnd = minutesArray[0] + interval

      for (let i = 1; i < minutesArray.length; i++) {
        const currentMinutes = minutesArray[i]
        const expectedNext = rangeEnd

        // 检查是否连续（当前时间点应该等于上一个时间段的结束时间）
        if (currentMinutes === expectedNext) {
          // 连续，扩展结束时间
          rangeEnd = currentMinutes + interval
        } else {
          // 不连续，保存当前时间段，开始新的时间段
          ranges.push([minutesToTime(rangeStart), minutesToTime(rangeEnd)])
          rangeStart = currentMinutes
          rangeEnd = currentMinutes + interval
        }
      }

      // 保存最后一个时间段
      ranges.push([minutesToTime(rangeStart), minutesToTime(rangeEnd)])

      return ranges
    },
    // 根据电价方案数据和月份回显电价配置
    loadPriceConfigFromScheme() {
      if (!this.priceSchemeData || !this.selectedMonth) {
        return
      }

      try {
        // 解析 priceJson
        const priceJson = JSON.parse(this.priceSchemeData.priceJson)
        const monthKey = `M${this.selectedMonth}`
        const monthData = priceJson[monthKey]

        if (!monthData || !Array.isArray(monthData) || monthData.length === 0) {
          return
        }

        const data = monthData[0]
        const interval = parseInt(data.SJJG || 15, 10) // 时间间隔，默认15分钟

        // 费率类型映射：FL1=尖峰，FL2=高峰，FL3=平段，FL4=低谷，FL5=深谷
        const rateTypeMap = {
          FL1: 'peak',
          FL2: 'high',
          FL3: 'flat',
          FL4: 'offPeak',
          FL5: 'superOffPeak'
        }

        // 更新每个费率类型的价格和时段
        Object.keys(rateTypeMap).forEach((flKey) => {
          const type = rateTypeMap[flKey]
          const priceKey = `${flKey}DJ` // 价格字段：FL1DJ, FL2DJ等
          const periodKey = `${flKey}QJ` // 时段字段：FL1QJ, FL2QJ等

          // 更新价格（不四舍五入，保持原始值）
          if (data[priceKey]) {
            this.$set(
              this.localPriceConfig[type],
              'price',
              String(data[priceKey])
            )
          }

          // 更新时段
          if (data[periodKey]) {
            const timePeriods = this.parseTimePeriods(data[periodKey], interval)
            this.$set(
              this.localPriceConfig[type],
              'timePeriods',
              timePeriods.length > 0 ? timePeriods : [null]
            )
          } else {
            // 如果没有时段数据，设置为空数组
            this.$set(this.localPriceConfig[type], 'timePeriods', [null])
          }
        })

        this.emitUpdate()
      } catch (error) {
        console.error('解析电价方案数据失败:', error)
      }
    },
    emitUpdate() {
      this.$emit('update:price-config', { ...this.localPriceConfig })
    }
  }
}
</script>

<style lang="scss" scoped>
.price-config {
  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .price-content {
    width: 80%;
    margin: 0 auto;
  }

  .price-item {
    display: flex;
    align-items: flex-start;
    justify-content: center;
    margin-bottom: 30px;
    padding: 15px;

    .price-left {
      display: flex;
      align-items: center;
      margin-right: 40px;
      flex-shrink: 0;
      height: 32px; // 与第一个时段选择器对齐

      .price-label {
        font-weight: bold;
        margin-right: 10px;
      }

      .price-unit {
        color: #909399;
      }
    }

    .price-right {
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      .time-period-container {
        display: flex;
        align-items: flex-start;

        .time-period-label {
          font-weight: bold;
          margin-right: 10px;
          width: 80px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          height: 32px; // 与第一个时段选择器高度对齐
        }

        .time-periods-wrapper {
          display: flex;
          flex-direction: column;
          flex: 1;

          .time-period-item {
            display: flex;
            align-items: center;
            height: 32px;
            margin-bottom: 10px;

            &:first-child {
              margin-bottom: 10px;
            }

            &:last-child {
              margin-bottom: 0;
            }

            .el-button {
              display: inline-flex;
              align-items: center;
              justify-content: center;

              i {
                font-size: 25px;
              }
            }
          }
        }
      }
    }
  }

  .price-curve {
    margin-top: 40px;

    .curve-chart {
      height: 260px;
      border-radius: 4px;
      padding: 15px 20px;
      background: #fff;
    }
  }
}
</style>
